//
//  WeiXinPayController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/12/4.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#define KLeftSpace 15
#define KRightSpace 15
#define KTopSpace 20


//untils
#import "Global.h"
#import "UIColor+Hex.h"
#import "UIImage+ColorToImage.h"
#import "NSString+Conversion.h"
#import "AppDelegate.h"
#import "ManagerHttpBase.h"
#import "ManagerGlobeUntil.h"
#import "UserInfoModel.h"
#import "FMDBManager.h"
//controller
#import "MyGoodsSureOrderController.h"
#import "SureOrderController.h"
//vendor
#import "RDVTabBarController.h"
#import "WeiXinPayController.h"
#import "WeiXinPayResultController.h"
//vendor
#import "WXApi.h"
#import "WXApiObject.h"
#import "MTA.h"
//支付宝
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"
#import "APAuthV2Info.h"

@interface WeiXinPayController ()

@property (nonatomic,strong)UILabel *orderNumber;
@property (nonatomic,strong)UILabel *orderPrice;

@property (nonatomic,strong)UILabel *price;
@property (nonatomic,strong)UIButton *surePay;
@property (nonatomic,strong)UIButton *weixinseleted;
@property (nonatomic,strong)UIButton *zhifubaoseleted;
@property (nonatomic,strong)NSString *flag;
@end

@implementation WeiXinPayController

- (void)viewDidLoad {
    self.title=@"确认支付";
    [super viewDidLoad];
    [self setUpSuberView];
    [self setUpdateData];
    [self addBackNavItem];
    [[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(weiXinBack:) name:WEIXINPAYRESULT object:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
    //清除数据库购物车表里的 下订单商品
    [self deleteDataWithFMDBShoppingCat];
    _flag =@"1";
    _weixinseleted.selected=YES;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"支付页面"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"支付页面"];
}
#pragma mark --清除数据库 商品数据
-(void)deleteDataWithFMDBShoppingCat
{
    if (self.orderNum.length!=0) {
//        NSLog(@"%@",self.goodIDs);
        
        NSMutableArray * goodIDs=[NSMutableArray arrayWithArray:[self.goodIDs componentsSeparatedByString:@","]];
        
        XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
        for (NSInteger i=0;i<goodIDs.count; i++) {
            [[FMDBManager sharedManager]deleteOneDataWithShopID:[NSString stringISNull:mode.storeID] goodID:[goodIDs objectAtIndex:i]];
        }
        
        NSMutableArray * selfGoods=[NSMutableArray arrayWithArray:[self.selfGoodIDs componentsSeparatedByString:@","]];
        for (NSInteger i=0;i<selfGoods.count; i++) {
            [[FMDBManager sharedManager]deleteOneDataWithgoodID:[selfGoods objectAtIndex:i]];
        }

    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:NO];
    
}
#pragma marl -- 请求数据
-(void)loadPayData
{
/* SIGNATURE			设备识别码   
 TOKEN			用户签名
   ORDERNUM			订单号
   FLAG			1:微信支付 2：支付宝支付
    目前只支持微信支付
 
 MSG = "";
 OBJECT =     {
 APPID = wxb595a449fa9ba651;
 NONCESTR = oukp4dz2mb72exuueejzpylgxhx5b90m;
 PACKAGE = "Sign=WXPay";
 PARTNERID = 1288445201;
 PREPAYID = wx20151205150159269f529c1d0423858507;
 SIGN = E6CA4E3F1A7B7EAEEE3D0866D9CE85FF;
 TIMESTAMP = 1449298897;
 };
 STATE = 0;
 **/
      NSString * adapterstr=[self.requestDataType isEqualToString:@"1"]?@"order/pay":@"service/order/pay";
    if(self.homeMakeType.length!=0)
    {
        adapterstr=@"ser/order/pay";
    }
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    UserInfoModel *mode = [[ManagerGlobeUntil sharedManager] getUserInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.token] forKey:@"TOKEN"];
    [parameter setObject:_orderNum forKey:@"ORDERNUM"];
    [parameter setObject:_flag forKey:@"FLAG"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:adapterstr success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            NSString *msg = [dataDic objectForKey:@"MSG"];
            
            if ([state isEqualToString:@"0"]) {//请求成功
                NSDictionary *data = [dataDic objectForKey:@"OBJECT"];
                if ([_flag isEqualToString:@"1"]) {
                    [weakSelf loadWeiXinPayDataWithDictionary:data];
                }else if([_flag isEqualToString:@"2"])
                {
                    [weakSelf loadZhiFuBaoPayDataWithDictionary:data];
                }
                
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }

        }
        
    } failure:^(bool isFailure) {
        
         [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
    }];
}
-(void)loadWeiXinPayResult
{
//    SIGNATURE			设备识别码
//    TOKEN			用户签名
//    ORDERNUM			订单号
    NSString * adapterstr=[self.requestDataType isEqualToString:@"1"]?@"order/query":@"service/order/query";
    if(self.homeMakeType.length!=0)
    {
        adapterstr=@"ser/order/query";
    }
    UserInfoModel *mode = [[ManagerGlobeUntil sharedManager] getUserInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.token] forKey:@"TOKEN"];
    [parameter setObject:_orderNum forKey:@"ORDERNUM"];
    __weak typeof(self)weakSelf = self;

    [manager parameters:parameter customPOST:adapterstr success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
//            NSString *msg = [dataDic objectForKey:@"MSG"];
//            NSLog(@"%@",msg);
            if ([state isEqualToString:@"0"]) {//请求成功
                NSString *payState =[NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"PAYSTATE"]];
                //            订单支付状态
                //            1：已支付，0：未支付
                if ([payState isEqualToString:@"1"]) {
                    [weakSelf pushPayResultWithState:@"0"];
                }else {
                    [weakSelf pushPayResultWithState:@"-1"];
                }
                
            }else {//请求失败
                [weakSelf pushPayResultWithState:@"-1"];
            }

        }
        
    } failure:^(bool isFailure) {
        
            [weakSelf pushPayResultWithState:@"-1"];
    }];

}
#pragma mark -- 微信方法
-(void)loadWeiXinPayDataWithDictionary:(NSDictionary *)dataDic
{
    if ([WXApi isWXAppInstalled]) {//已安装微信
        if (dataDic.count != 0) {
            PayReq *request = [[PayReq alloc]init];
            request.partnerId           = [NSString stringTransformObject:[dataDic objectForKey:@"PARTNERID"]];
            request.prepayId            = [NSString stringTransformObject:[dataDic objectForKey:@"PREPAYID"]];
            request.nonceStr            = [NSString stringTransformObject:[dataDic objectForKey:@"NONCESTR"]];
            request.timeStamp           = [[NSString stringTransformObject:[dataDic objectForKey:@"TIMESTAMP"]] intValue];
            request.package             = [NSString stringTransformObject:[dataDic objectForKey:@"PACKAGE"]];
            request.sign                = [NSString stringTransformObject:[dataDic objectForKey:@"SIGN"]];
            if ([WXApi sendReq:request]) {
                
            } else {
                
            }
        }

    } else {//未安装微信
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"您还未安装微信" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
   }
}
#pragma mark -- 支付宝 请求方法
-(void)loadZhiFuBaoPayDataWithDictionary:(NSDictionary *)dataDic
{

     NSString *appScheme = @"dashihuiALiPay";
    if (dataDic.count !=0) {
        NSString *orderString = nil;
        orderString =[NSString stringTransformObject:[dataDic objectForKey:@"PARAMS"]];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //            NSLog(@"reslut = %@",resultDic);
            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
                [self loadWeiXinPayResult];
            }else{
                [self pushPayResultWithState:@"-1"];
            }
        }];
    }

}

#pragma mark -- button Action
//确认支付按钮
-(void)surePayClick:(UIButton*)sender
{
    
        if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
          [self loadPayData];
        }
}
//支付宝 微信 二选一 设置
-(void)buttonClick:(UIButton *)sender
{
    UIButton *button=(UIButton *)sender;
    button.selected=YES;
    if (button.tag==1) {
        _zhifubaoseleted.selected=NO;
        _flag =@"1";
    }else
    {
        _weixinseleted.selected=NO;
         _flag =@"2";
    }
    
}
-(void)backBtnAction:(id)sender
{
    for (UIViewController*VC in self.navigationController.childViewControllers) {
        if ([VC isKindOfClass:[SureOrderController class]] || [VC isKindOfClass:[MyGoodsSureOrderController class]]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- NSNotification
- (void)weiXinBack:(NSNotification*)noti {
    NSDictionary *dataDic = [noti userInfo];
    NSString *state = [dataDic objectForKey:@"state"];
    if ([state isEqualToString:@"0"]) {
        [self loadWeiXinPayResult];
    }else{
        [self pushPayResultWithState:state];
    }
   
}
-(void)pushPayResultWithState:(NSString *)state
{
    WeiXinPayResultController *weiXinPayResultVC = [[WeiXinPayResultController alloc]init];
    weiXinPayResultVC.state = state;
    weiXinPayResultVC.homeMakeType = self.homeMakeType;
    weiXinPayResultVC.orderNum = [NSString stringISNull:self.orderNum];
    weiXinPayResultVC.requestDataType =self.requestDataType;
    [self.navigationController pushViewController:weiXinPayResultVC animated:YES];

}
#pragma mark -- 赋值
-(void)setUpdateData
{
    _orderNumber.text=[NSString stringWithFormat:@"订单号:%@",self.orderNum];
    if ([self.requestDataType isEqualToString:@"0"]) {//商品订单去掉订单总价,只有服务订单包含订单总价 requestDataType  商品订单 是1 服务订单是 0
        _orderPrice.text=[NSString stringWithFormat:@"订单总价:￥%@",self.totalPrice];
    }
    _price.text=[NSString stringWithFormat:@"￥%@",self.totalPrice];
}
#pragma mark--初始化控件
-(void)setUpSuberView
{
    self.view.backgroundColor=[UIColor colorWithHexString:@"#efefef"];
    CGFloat viewHight = 0;
     if ([self.requestDataType isEqualToString:@"0"]) {//商品订单去掉订单总价,只有服务订单包含订单总价 requestDataType  商品订单 是1 服务订单是 0
         viewHight = 330;
     } else {
         viewHight = 330 - 20 - KTopSpace;
     }
    UIView *view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, viewHight)];
    view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:view];
    _orderNumber=[[UILabel alloc]initWithFrame:CGRectMake(KLeftSpace, KTopSpace, VIEW_WIDTH-KLeftSpace-KRightSpace,20)];
    _orderNumber.font=[UIFont systemFontOfSize:16];
    _orderNumber.textColor=[UIColor colorWithHexString:@"#000000"];
    _orderPrice.text=@"232313123123123";
    [view addSubview:_orderNumber];
    
    CGFloat y = 0;
    if ([self.requestDataType isEqualToString:@"0"]) {//商品订单去掉订单总价,只有服务订单包含订单总价 requestDataType  商品订单 是1 服务订单是 0
        _orderPrice=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.orderNumber.frame), CGRectGetMaxY(self.orderNumber.frame)+KTopSpace, CGRectGetWidth(self.orderNumber.bounds), CGRectGetHeight(self.orderNumber.bounds))];
        _orderPrice.font=[UIFont systemFontOfSize:16];
        _orderPrice.text=@"0";
        [view addSubview:_orderPrice];
        y = CGRectGetMaxY(self.orderPrice.frame)+KTopSpace;
        
    } else {
        y = CGRectGetMaxY(self.orderNumber.frame)+KTopSpace;
    }
    
    
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.orderNumber.frame),y, VIEW_WIDTH/2, CGRectGetHeight(self.orderNumber.bounds))];
    label.textColor=[UIColor colorWithHexString:@"#000000"];
    label.font=[UIFont systemFontOfSize:16];
    label.text=@"使用第三方平台支付";
    [view addSubview:label];
    
    _price=[[UILabel alloc]initWithFrame:CGRectMake(VIEW_WIDTH/2-15, CGRectGetMinY(label.frame),VIEW_WIDTH/2,CGRectGetHeight(label.bounds))];
    _price.font=[UIFont systemFontOfSize:16];
    _price.textColor=[UIColor colorWithHexString:@"#c52720"];
    _price.textAlignment=NSTextAlignmentRight;
    _price.text=@"0";
    [view addSubview:_price];
    //分割线
    UILabel *space=[[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.price.frame)+KTopSpace, VIEW_WIDTH, 1)];
    space.backgroundColor=[UIColor colorWithHexString:@"#dddddd"];
    [view addSubview:space];
    //微信logo
    UIImageView *weiXinLogo=[[UIImageView alloc]initWithFrame:CGRectMake(KLeftSpace, CGRectGetMaxY(space.frame)+KTopSpace, 50, 50)];
    weiXinLogo.image=[UIImage imageNamed:@"weixinicon"];
    [view addSubview:weiXinLogo];
    //微信文字
    UILabel *weixin=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(weiXinLogo.frame)+KLeftSpace, CGRectGetMidY(weiXinLogo.frame)-10, 100, 20)];
    weixin.text=@"微信支付";
    weixin.font=[UIFont systemFontOfSize:16];
    weixin.textColor=[UIColor colorWithHexString:@"#000000"];
    [view addSubview:weixin];
    // 微信选中按钮
    _weixinseleted=[[UIButton alloc]initWithFrame:CGRectMake(VIEW_WIDTH-KRightSpace-40, CGRectGetMinY(weixin.frame)-10, 40, 40)];
    UIImage *seletedimage=[UIImage imageNamed:@"checkBoxSelectdImage"];
    UIImage *normalimage=[UIImage imageNamed:@"checkBoxNormalImage"];
    [_weixinseleted setImage:normalimage forState:UIControlStateNormal];
    [_weixinseleted setImage:seletedimage forState:UIControlStateSelected];
    [_weixinseleted addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    _weixinseleted.tag=1;
    [view addSubview:_weixinseleted];
    //分割线
    UILabel *spacetwo=[[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(weiXinLogo.frame)+KTopSpace, VIEW_WIDTH, 1)];
    spacetwo.backgroundColor=[UIColor colorWithHexString:@"#dddddd"];
    [view addSubview:spacetwo];
   //支付宝logo
    UIImageView *zhifubaoLogo=[[UIImageView alloc]initWithFrame:CGRectMake(KLeftSpace, CGRectGetMaxY(spacetwo.frame)+KTopSpace, 50, 50)];
    zhifubaoLogo.image=[UIImage imageNamed:@"icon_zhifubao"];
    [view addSubview:zhifubaoLogo];
    //支付宝文字
    UILabel *zhifubao=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(zhifubaoLogo.frame)+KLeftSpace, CGRectGetMidY(zhifubaoLogo.frame)-10, 100, 20)];
    zhifubao.text=@"支付宝支付";
    zhifubao.font=[UIFont systemFontOfSize:16];
    zhifubao.textColor=[UIColor colorWithHexString:@"#000000"];
    [view addSubview:zhifubao];
    //支付宝选中按钮
    _zhifubaoseleted=[[UIButton alloc]initWithFrame:CGRectMake(VIEW_WIDTH-KRightSpace-40, CGRectGetMinY(zhifubao.frame)-10, 40, 40)];
    [_zhifubaoseleted setImage:normalimage forState:UIControlStateNormal];
    [_zhifubaoseleted setImage:seletedimage forState:UIControlStateSelected];
    [_zhifubaoseleted addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    _zhifubaoseleted.tag=2;
    [view addSubview:_zhifubaoseleted];
    
    UILabel *spacethree=[[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view.frame)-1, VIEW_WIDTH, 1)];
    spacethree.backgroundColor=[UIColor colorWithHexString:@"#dddddd"];
    [view addSubview:spacethree];

    
    //退出登录按钮视图
    UIImage *btnBG = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#0093dd"] frame:CGRectMake(0, 0, VIEW_WIDTH - 2*KLeftSpace, 44)];
    _surePay = [UIButton buttonWithType:UIButtonTypeCustom];
    _surePay.frame = CGRectMake(KLeftSpace
                                , VIEW_HEIGHT-64-44-20
                                , VIEW_WIDTH - 2*KLeftSpace, 44);
    _surePay.titleLabel.font = [UIFont systemFontOfSize:16];
    [_surePay setBackgroundImage:btnBG forState:UIControlStateNormal];
    [_surePay setTitle:@"确认支付" forState:UIControlStateNormal];
    [_surePay setTitleColor:[UIColor colorWithHexString:@"#ffffff"] forState:UIControlStateNormal];
    [_surePay.layer setMasksToBounds:YES];
    [_surePay addTarget:self action:@selector(surePayClick:) forControlEvents:UIControlEventTouchUpInside];
    [_surePay.layer setCornerRadius:3];
    [self.view addSubview:_surePay];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
